#define _CRT_SECURE_NO_WARNINGS

#include "dynamic_array.h"

void InitiArray(dynamic_arr* arr, int capacity)
{
	arr->data = (int*)malloc(capacity * sizeof(int));
	if (arr->data == nullptr)
	{
		fprintf(stderr, "memory allocation failed\n");
		exit(-1);
	}
	arr->size = 0;
	arr->capacity = capacity;

}

void Insert(dynamic_arr* arr, int value)
{
	if (arr->size == arr->capacity)
	{
		int new_capacity =  arr->capacity *= 2;
		int* new_data = (int*)realloc(arr->data,new_capacity * sizeof(int));
		if (new_data == nullptr)
		{
			fprintf(stderr, "memory allocation failed\n");
			free(arr->data);
			exit(-1);
		}

		arr->data = new_data;
		arr->capacity = new_capacity;

	}

	arr->data[arr->size++] = value;
}

void DeleteIndex(dynamic_arr* arr, int index)
{
	if (index < 0 || index > arr->size)
	{
		fprintf(stderr, "index out of range\n");
		return;
	}

	if (index < arr->size - 1)
	{
		for (int i = index; i < arr->size - 1; i++)
		{
			arr->data[i] = arr->data[i + 1];
		}
	}
	arr->size--;

	if (arr->size == 0)
	{
		free(arr->data);

		arr->data = nullptr;
		arr->capacity = 0;
	}
	else if (arr->size < arr->capacity / 4 && arr->capacity / 2 >= 2)
	{
		int new_capacity = arr->capacity /= 2;
		int* new_data = (int*)realloc(arr->data, new_capacity);
		if (new_data != nullptr)
		{
			arr->data = new_data;
			arr->capacity = new_capacity;
		}
	}
}

void DeleteValue(dynamic_arr* arr, int value)
{
	for (int i = 0; i < arr->size; i++)
	{
		if (arr->data[i] == value)
		{
			DeleteIndex(arr, i);
			i--;
			break;
		}
	}

	return;
}

void Traverse(dynamic_arr* arr)
{
	for (int i = 0; i < arr->size; i++)
	{
		printf("%d ",arr->data[i]);
	}
	printf("\n");
}

void DeleAllElements(dynamic_arr* arr)
{
	while (arr->size > 0)
	{
		DeleteIndex(arr, 0);
	}
}

void FreeArray(dynamic_arr* arr)
{
	free(arr->data);
	arr->data = NULL;
	arr->capacity = 0;
	arr->size = 0;

}



int main()
{
	dynamic_arr arr;
	pdynamic_arr parr = &arr;
	InitiArray(&arr, 2);
	printf("array capacity:%d \n", parr->capacity);

	Insert(parr, 9);
	Traverse(parr);

	Insert(parr, 29);
	Traverse(parr);

	Insert(parr, 47);
	Traverse(parr);
	printf("array capacity:%d \n", parr->capacity);

	DeleteIndex(parr, 0);
	Traverse(parr);

	DeleteIndex(parr, 1);
	Traverse(parr);

	FreeArray(parr);


	return 0;
}